package com.leo.foodmaster.admin.stock.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.leo.foodmaster.admin.stock.entity.Warehouse;
import com.leo.foodmaster.admin.stock.entity.WarehouseUser;
import com.leo.foodmaster.admin.stock.mapper.WarehouseMapper;
import com.leo.foodmaster.admin.stock.service.IWarehouseService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leo.foodmaster.admin.stock.service.IWarehouseUserService;
import com.leo.foodmaster.admin.system.entity.SysUser;
import com.leo.foodmaster.admin.system.service.IUserService;
import com.leo.foodmaster.commons.entity.Result;
import com.leo.foodmaster.commons.util.WebUtils;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 仓库管理 服务实现类
 * </p>
 *
 * @author Leo
 * @since 2021-08-15
 */
@Service
@AllArgsConstructor
public class WarehouseServiceImpl extends ServiceImpl<WarehouseMapper, Warehouse> implements IWarehouseService {
    private final IWarehouseUserService warehouseUserService;
    private final IUserService userService;

    /**
     * 条件分页查询仓库列表
     * @param page 分页参数
     * @param name 仓库名称
     * @param status  仓库状态
     * @return IPage<Warehouse>
     */
    @Override
    public IPage<Warehouse> getWarehousePageList(Page<Warehouse> page, String name, String status) {
        Long organId = WebUtils.getUser().getOrganId();
        LambdaQueryWrapper<Warehouse> qw = Wrappers.lambdaQuery(Warehouse.class)
                .eq(Warehouse::getOrganId, organId)
                .eq(StrUtil.isNotBlank(name), Warehouse::getName, name)
                .eq(StrUtil.isNotBlank(status), Warehouse::getStatus, status);
        Page<Warehouse> pageList = page(page, qw);
        List<Warehouse> records = pageList.getRecords();
        for (Warehouse warehouse : records) {
            List<Long> collect = Arrays.stream(warehouse.getFoodMaterialTypeId().split(",")).map(Long::parseLong).collect(Collectors.toList());
            warehouse.setFoodMaterialType(collect);
            List<WarehouseUser> list = warehouseUserService.list(Wrappers.lambdaQuery(WarehouseUser.class)
                    .eq(WarehouseUser::getWarehouseId, warehouse.getId()));
            List<Long> userIds = list.stream().map(WarehouseUser::getUserId).collect(Collectors.toList());
            warehouse.setAdminIdList(userIds);
            if (!userIds.isEmpty()) {
                List<SysUser> userList = userService.list(Wrappers.lambdaQuery(SysUser.class)
                        .in(SysUser::getId, userIds));
                warehouse.setAdminList(userList);
            }
        }
        return pageList;
    }

    /**
     * 新增仓库
     * @param warehouse 仓库信息
     * @return Result<Object>
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Object> addWarehouse(Warehouse warehouse) {
        warehouse.setOrganId(WebUtils.getUser().getOrganId());
        List<SysUser> adminList = warehouse.getAdminList();
        warehouse.setAdminId(adminList.get(0).getId());
        warehouse.setAdminName(adminList.get(0).getName());
        warehouse.setAdminPhone(adminList.get(0).getPhone());
        warehouse.setSerialNum("CK-" + System.currentTimeMillis());
        // 新增仓库
        save(warehouse);
        // 新增仓库——仓库管理员关系表
        List<WarehouseUser> warehouseUsers = new ArrayList<>();
        for (SysUser sysUser : adminList) {
            warehouseUsers.add(new WarehouseUser(warehouse.getId(), sysUser.getId(), sysUser.getPhone()));
        }
        warehouseUserService.saveBatch(warehouseUsers);
        return Result.success();
    }

    /**
     * 修改仓库
     * @param warehouse 仓库信息
     * @return Result<Object>
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Object> updateWarehouse(Warehouse warehouse) {
        // 删除，再新增仓库——仓库管理员关系表
        warehouseUserService.remove(Wrappers.lambdaUpdate(WarehouseUser.class)
                .eq(WarehouseUser::getWarehouseId, warehouse.getId()));
        List<SysUser> adminList = warehouse.getAdminList();
        List<WarehouseUser> warehouseUsers = new ArrayList<>();
        for (SysUser sysUser : adminList) {
            warehouseUsers.add(new WarehouseUser(warehouse.getId(), sysUser.getId(), sysUser.getPhone()));
        }
        warehouseUserService.saveBatch(warehouseUsers);

        // 修改仓库信息
        warehouse.setAdminId(adminList.get(0).getId());
        warehouse.setAdminName(adminList.get(0).getName());
        warehouse.setAdminPhone(adminList.get(0).getPhone());
        updateById(warehouse);

        return Result.success();
    }
}
